package net.yc.imalachat.push;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.example.factory.Factory;
import com.example.factory.data.helper.AccountHelper;
import com.example.factory.persistence.Account;
import com.igexin.push.GtPushInterface;
import com.igexin.sdk.PushConsts;

/**
 * @author:0.2℃
 * @date： 2022-01-05 13:45
 * @version:
 * @Description ：个推广播接收器
 */
public class MessageReceiver extends BroadcastReceiver {
    private static final String TAG = MessageReceiver.class.getSimpleName();
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null) {
            return;
        }
        Bundle bundle = intent.getExtras();

        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_CLIENTID:
                Log.i(TAG, "GET_CLIENTID: " + bundle.toString());
                // 当id初始化的时候
                // 获取设备id，这是个推框架给定的参数值
                onClientInit(bundle.getString("clientid"));
                break;
            case PushConsts.GET_MSG_DATA:
                // 常规消息送达
                byte[] payload = bundle.getByteArray("payload");
                if (payload != null) {
                    String msg = new String(payload);
                    Log.i(TAG, "GET_MSG_DATA :" + msg);
                    onMessageArrived(msg);
                }
                break;
            default:
                Log.i(TAG, "OTHER:" + bundle.toString());
                break;
        }
    }

    /**
     * 当id初始化的时候
     * @param cid 设备id
     */
    private void onClientInit(String cid) {
        // 设置设备的id
        Account.setPushId(cid);
        if (Account.isLogin()) {
            // 账户登录状态，进行一个pushId绑定
            // 如果没有登录，是不能进行绑定的
            AccountHelper.bindPush(null);
        }
    }

    /**
     * 消息送达的时候
     * @param message 新消息
     */
    private void onMessageArrived(String message) {
        // 交给Factory处理
        Factory.dispatchPush(message);
    }
}
